// JavaScript Document
define(function(require,exports,module){
	require('easyui');
	require('easyui-css');
	require('mod-multiAreaSel-css');
	var MultiArea = require('mod-multiAreaSel');
	var util      = require('lm-util');

	exports.active = function(menu, submenu, status){
		if ($('#'+menu).length) {
			$('#'+menu).addClass('current');
            var index = $('#'+menu).index("dt");
            if($('#'+menu).hasClass('unlink')){
                $('#'+menu).siblings("dd").eq(index).show();
                openSide[index]=true;
            }
		}
		if ($('#'+submenu).length) {
			$('#'+submenu).addClass('current');
		}
		if ($('#'+status).length) {
			$('#'+status).addClass('current');
		}
        var sIndex = status.split('_')[1];
        if ($('#status_con_'+sIndex).length) {
            $('#status_con_'+sIndex).show().siblings('tbody').hide();
        }
	};

	//侧边栏
    var len = $(".sidebar>dl>dt.unlink").length,openSide = [];
    for(var i = 0; i<len; i++){
        openSide[i] = false;
    }
	(function(){
		$(".sidebar>dl>dt.unlink").each(function(index){
			$(this).click(function(e) {
                var $subMenu = $(this).siblings("dd").eq(index);
                if(openSide[index]){
                    $subMenu.slideUp();
                    openSide[index] = false;
                }else{
					$subMenu.slideDown().siblings('dd').slideUp();
                    for(var i=0;i<len; i++){
                        if(i==index){openSide[i] = true;}
                        else{openSide[i] = false;}
                    }
				}
			});
		});
	})();

	//修改资料
	(function(){
		$("#data-nav>li").each(function(index, element) {
			$(this).click(function(e) {
				$(this).addClass("current").siblings().removeClass("current");
				$("#data-tb>tbody").eq(index).show().siblings("tbody").hide();
			});
		});
	})();

	//表格鼠标滑过当前行着色
	(function(){
        if($(".filter-tb").length<=0) return;
        $(".filter-tb").find("tr").hover(function(){
            $(this).addClass("over");
        },function(){
            $(this).removeClass("over");
        })
	})();

	//全选
	(function(){
        if($("#sel-all").length<=0) return;
		var $checks = $("#pub-list").find("input"),
			len = $checks.length;
		$("#sel-all").click(function(){
			var check = $(this).prop("checked");
			$checks.prop("checked",check);
		});
		$checks.click(function(){
			var check = $(this).prop("checked");
			if(!check){
				$("#sel-all").prop("checked",check);
			}else{
				var checkNum = 0;
				$checks.each(function(index, element) {
					if($(this).prop("checked")){checkNum++;}
				});
				if(checkNum == len){
					$("#sel-all").prop("checked",check);
				}
			}
		});
	})();

//关注车型
    function operOwner($oper){
        $oper.click(function(){
            var action = $(this).attr('action'),
                act = $(this).attr('act'),
                amid = $(this).attr('amid'),
                itemid = $(this).attr('itemid'),
                bytime = $(this).attr('bytime'),
                title,
                focusNum = $(".js-focus-car").length;
            if(focusNum>=3 && act=='car'){
                $('#warning').dialog('open');
                return;
            }
	        if(act =='edit' || act == 'editcar'){ title = "修改车型"; $('#carbtn').html('修改车型')}
            else if(act=='car' || act == 'addcar'){  title = "添加车型"; $('#carbtn').html('添加车型') }
	        if(act == 'addcar' || act == 'editcar'){$('#by').hide()}
            $("#dlg").dialog({
                title:title,
                closed:true,
                modal:true,
                width:400,
                height:250
            });
	        $('#itemid').val(itemid);
	        $('#action').val(act);
	        util.makeRequest(lemon.site_url+'api/member/my.php',{action:action,aMid:amid,bytime:bytime}, function(re){
				var decodedValue = $.parseJSON(re);
		        if (!decodedValue.errNo) {
			        $('#ownerCarEdit').html(decodedValue.msg);
			        $('#bytime').html(decodedValue.bytime);
			        $("#dlg").dialog('open');
		        }
	        })

        });
    }
    if($('#addCar')){operOwner($('#addCar'));}
    if($('.edit')){operOwner($('.edit'));}

    $('#closeDlg').click(function(){
        $("#dlg").dialog('close');
    });
    //地图标注
    (function(){
        if($("#markLoc").length<=0) return;
        $("#markLoc").click(function(){
            var w = $('body').width(),h = $('body').height(),
                moveLeft = w-550,
                moveTop =  h-440;
            var cityId = $("#post_areaid_").val(),
                detailAddr = $("input[name='post[address]']").val(),
                cityName,wholeAdd;
            $.ajax({
                async : false,
                cache : false,
                type : 'post',
                dataType:'json',
                url : lemon.site_url+'api/ajax.php',
                data : 'aM=common&aA=areapos&aId='+cityId,
                success : function(data){
                    cityName = data.content;
                }
            });
            wholeAdd = cityName;

            if(wholeAdd.length>1){
                var oldrUrl = $("#mapDlg").find('iframe').attr("src");
                var wholeAddIdenx = oldrUrl.indexOf('wholeAdd');
                if(wholeAddIdenx>0){
                    oldrUrl = oldrUrl.substring(0,wholeAddIdenx-1);
                }
                var newUrl = oldrUrl+"&wholeAdd="+encodeURI(wholeAdd.substring(2));
                $("#mapDlg").find('iframe').attr('src',newUrl);
            }
            $("#mapDlgWrap").show();
            $("#mapDlg").dialog({
                modal:true,
                width:540,
                height:430,
                left:moveLeft,
                top:moveTop,
                closed:false
            });
        });
    })();

	//每隔30秒获取新邮件，新对话
	function sendajax(){
		$.getJSON(lemon.site_url+"ajax.php"+"?callback=?",{'action':"new"},function(data){
			if(data){
				$('#ixdcw_message').html(data.message > 0 ? '未读信息('+data.message+')':'未读信息(0)');
				$('#ixdcw_chat').html(data.chat  > 0 ? '新对话('+data.chat +')':'暂无新对话');
			}
		});
	}
	sendajax();
	setInterval(function(){sendajax()},30000);


    //广告位
    (function(){
        if($(".jsDefault").length<=0) return;
        $(".jsDefault").click(function(){
            var isDefault = $(this).prop("checked");
            if(isDefault){
                $(this).parents("tr.tb-hd").nextUntil(".tb-hd,.tb-sbt").hide();
            }else{
                $(this).parents("tr.tb-hd").nextUntil(".tb-hd,.tb-sbt").show();
            }
        });
    })();
    (function(){
        if($("#ad-buy-form").length<=0) return;
        if($("#ad-rule-agree").prop("checked")){
            $("#ad-buy-sbt").removeClass("btn-dis");
        }else{
            $("#ad-buy-sbt").addClass("btn-dis");
        }
        $("#ad-rule-agree").on("click",function(){
            var isAgree = $(this).prop("checked");
            if(isAgree){
                $("#ad-buy-sbt").removeClass("btn-dis");
            }else{
                $("#ad-buy-sbt").addClass("btn-dis");
            }
        });

        //购买广告位
        $("#ads-time").keyup(function(){
            var time = $.trim($(this).val())=="" ? 0 : parseInt($.trim($(this).val())),
                totalPrice = time * parseInt($.trim($("#ads-price").val()));
            $("#ads-total").text(totalPrice);
        });
        //获取广告位价格
        function getPrice(url,options){
            $.ajax({
                type:"GET",
                url:url,
                data:options,
                dataType:"json",
                contentType:"application/json;charset=utf-8",
                success:function(data){
                    if(data){
                        var time = $.trim($("#ads-time").val())=="" ? 0 : parseInt($.trim($("#ads-time").val()));
                        var totalPrice = time * parseInt(data.price);
                        $("#ads-price").val(data.price);
                        $("#ads-total").text(totalPrice);
                    }
                }
            });
        }
        //选择类型跳转页面
        $("#ads-type").change(function(){
            var urlId = $(this).val(),
                url="ad.php?action=add2&pid="+urlId;
            console.log(url)
            window.location.href = url;
        });
        //主站
        $("#site-main").click(function(){
            var pid = $("#ads-type").val();
            $("#ads-prov").hide();
            $("#ads-city").hide();
            $("#ads-time").val(1);
            getPrice("ajax.php",{action:"getprice",pid:pid,isstaion:1});
        });
        //分站
        $("#site-sub").click(function(){
            $("#ads-prov").find("input[type=checkbox]").prop("checked",false);
            $("#ads-prov").show();
            $("#ads-time").val("");
            $("#ads-total").text("");
        });
        //获取省对应的市
        $("#ads-prov").find("input[type=checkbox]").click(function(){
            var pid = $("#ads-type").val(),
                provs = [];
            $("#ads-prov").find("input[type=checkbox]").each(function(){
                if($(this).prop("checked")){
                    provs.push($(this).val());
                }
            });
            if(provs.length<=0){
                $("#ads-city").hide();
                $("#ads-time").val("");
                $("#ads-total").text("");
                return;
            }
            $.ajax({
                type:"get",
                url:"ajax.php",
                data:{action:"getcity",pid:pid,provs:provs},
                dataType:"json",
                contentType:"application/json;charset=utf-8",
                success:function(data){
                    if(data){
                        $("#ads-city>td>div").text("")
                        for(var i in data){
                            var cityInput = '<label class="fn-left"><input name="post[cityid][]" value="'+data[i].cityId+'" class="nobd fn-left mr5" type="checkbox">'+data[i].cityName+'</label>';
                            $("#ads-city>td>div").append(cityInput);
                        }
                    }
                }
            });
            $("#ads-city").show();
        });
        //获取分站广告位价格
        $("#ads-city").on("click",'input[type=checkbox]',function(){
            var pid = $("#ads-type").val(),
                cities = [];
            $("#ads-city").find("input[type=checkbox]").each(function(){
                if($(this).prop("checked")){
                    cities.push($(this).val());
                }
            });
            if(cities.length<=0){
                $("#ads-total").text("");
                $("#ads-time").val("");
                return;
            }
            $("#ads-time").val(1);
            getPrice("ajax.php",{action:"getprice",pid:pid,cities:cities,isstaion:0});
        });
    })();

    (function(){
        if($(".pages").length<=0)return;
        $(".pages").find("input.submit").click(function(){
            var pageNum = $('#destoon_pageno').val();
            if(isNaN(pageNum) || $.trim(pageNum)=='' ){
                $('#destoon_pageno').select();
                return;
            }
            var url = $(this).attr('data-url').replace('\{destoon_page\}',pageNum);
            window.location.href = url;
        });
    })();

	//地区多选
	(function(){
		$("#J_SelectArea").click(function(){
			var appView = new MultiArea({
				areaIds:$("#J_AreaIds"),
				areaNames:$("#J_AreaNames"),
				cityIds:$("#J_CityIds"),
				dataUrl:lemon.site_url+"api/area/multiAreaSel.php"
			});
			$("body").append(appView.el);
		});
	})();

	//发布信息计费
	exports.charge = function(moduleid,groupid,username,areas){
		$.ajax({
			type:'POST',
			url:lemon.site_url+"ajax.php?module=common&action=charges",
			data:{moduleid:moduleid,groupid:groupid,username:username,areas:areas},
			dataType:'json',
			success:function(data){
				$('#citylen').val(data.citylen);
				$('#cityprice').val(data.message);
			}
		})
	};

	//发布信息充值提示
	$(".J_CloseDialog").click(function(){
		$("#J_PatDialog").hide();
	});
	$("#J_Charge").click(function(){
		$("#J_PatDialog").show();
	});

});